// src/utils/request.ts
import { useUserStore } from "@/store/modules/user";
// http请求根路径
const BASE_URL = `${import.meta.env.VITE_APP_API_URL}${import.meta.env.VITE_APP_BASE_API}`;

export default function httpRequest<T>(options: UniApp.RequestOptions): Promise<ResponseData> {
  const token = uni.getStorageSync("token");
  return new Promise((resolve, reject) => {
    const sendHttpRequest = (token: string) => {
      uni.request({
        ...options,
        url: `${BASE_URL}${options.url}`,
        header: {
          ...options.header, token: token
        },
        success: (response) => {
          const resData = response.data as ResponseData<T>;
          if (response.statusCode === 401) {
            // 401 未授权，尝试刷新 token
            handleTokenRefresh()
             .then(() => sendHttpRequest(uni.getStorageSync("token")))
             .catch((err) => {});
            return;
          }
          if (response.statusCode == 200) {
            resolve(resData);
            return;
          }
          reject({
            message: resData.message || "业务处理失败",
            code: resData.code,
          });
        },
        fail: (error) => {
          console.error("网络请求失败", error);
          reject({
            message: "网络请求失败",
            code: "01",
          });
        },
      });
    };

    sendHttpRequest(token);
  });
}

// 刷新 token
async function handleTokenRefresh(): Promise<void> {
  const refreshToken = uni.getStorageSync("refreshToken");
  if (!refreshToken) {
    redirectToLogin();
    throw new Error("未找到 refreshToken");
  }
  try {
    const response = await uni.request({
      url: `${BASE_URL}/atcp-auth/refresh-token?refreshToken=${refreshToken}`,
      method: "GET",
    });

    const resData = response.data as ResponseData<{ token: string; refreshToken: string }>;
    if (resData.code === "00") {
      uni.setStorageSync("token", resData.data.token);
      uni.setStorageSync("refreshToken", resData.data.refreshToken);
    } else {
      redirectToLogin();
      throw new Error(resData.message || "刷新 token 失败");
    }
  } catch (error) {
    redirectToLogin();
    throw error;
  }
}

// 跳转到登录页
function redirectToLogin() {
  const userStore = useUserStore();
  userStore.setLoginStatus(false);
  userStore.setToken("");
  userStore.setUserInfo(null);
  userStore.setMenus([]);
  userStore.setPermissions([]);
  uni.removeStorageSync("token");
  uni.removeStorageSync("refreshToken");
  uni.removeStorageSync("userInfo");
  uni.removeStorageSync("menus");
  uni.removeStorageSync("permissions");
  uni.reLaunch({
    url: "/pages/login/login",
  });
}
